﻿var map;
var geocoder;
var oMapPlace;



function initialize() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(41.535535, -8.628259), 15);
        map.addControl(new GLargeMapControl);
        map.addControl(new GMapTypeControl());

        GEvent.addListener(map, "error", handleErrors);
        GEvent.addListener(map, "click", getAddress);

        geocoder = new GClientGeocoder();

        setDirections();
    }
}



function getAddress(overlay, latlng) {
    if (latlng != null) {
        geocoder.getLocations(latlng, showAddress);
    }
}



function setEntityData() {
    var aEntityAddress = oMapPlace.address.split(","); 
    //entities editor fields
    var oForm = document.forms["formEntity"];
    var oAddress1 = oForm.elements["Address1"]
    var oAddress2 = oForm.elements["Address2"]
    var oPostalCode = oForm.elements["PostalCode"];
    var oCity = oForm.elements["City"];
    var oLatLng = oForm.elements["LatLng"];  
    //mark entity fields
    var oMForm = document.forms["entityMark"];

    try {
        //Fill Entity fiels (other than the address ones)
        oForm.elements["EntityAbbr"].value = oMForm.elements["ettCode"].value;
        oForm.elements["EntityName"].value = oMForm.elements["ettName"].value;
        oForm.elements["Phone"].value = oMForm.elements["ettPhone"].value;
        oForm.elements["Fax"].value = oMForm.elements["ettFax"].value;
        oForm.elements["Email"].value = oMForm.elements["ettEmail"].value;
        oForm.elements["URL"].value = oMForm.elements["ettURL"].value;
    
        //test if the address is known
        if (oMapPlace.AddressDetails.Accuracy == 0) {
            throw ("Endereço desconhecido.")
        }
    
        //clear the current fields
        oAddress1.value = "";
        oAddress2.value = "";
        oPostalCode.value = "";
        oCity.value = "";
        oLatLng.value = "";
        
        //Fill the country (allways exists)
        oAddress2.value = Trim(aEntityAddress.pop()); //the address2 field is filled with the country
        
        //Fill the postal code fields if accuracy >= 5
        if (oMapPlace.AddressDetails.Accuracy >= 5) { //if the address have a minimun postal code accuracy
            var aCP = Trim(aEntityAddress.pop()).split(" "); // with this accuracy the postal code allways exists
            var revACP = aCP.reverse();
            if (revACP.length > 0) { oPostalCode.value = Trim(revACP.pop()); }
            while (revACP.length > 0 ) {
                oCity.value = oCity.value + Trim(revACP.pop()) + " ";
            }
            oCity.value = oCity.value.slice(0, -1);
        }
        
        //fill the address1 field with all other address information
        var revAddress = aEntityAddress.reverse();
        while (revAddress.length > 0) {
            oAddress1.value = oAddress1.value + Trim(revAddress.pop()) + ", ";
        }
        oAddress1.value = oAddress1.value.slice(0, -2);
        
        //fill the coordinates field
        oLatLng.value = oMapPlace.Point.coordinates[1] + "," + oMapPlace.Point.coordinates[0];               
    }
    catch (err)
    {
        alert("Erro a definir o endereço da entidade\n\n" + err.description + "\n\nPrecisão: " + oMapPlace.AddressDetails.Accuracy + "\n\nEndereço: " + oMapPlace.address);
    }
}



function showAddress(response) {
    map.clearOverlays();
    if (!response || response.Status.code != 200) {
        handleErrors(response.Status.code);        
    } else {
        place = response.Placemark[0];
        oMapPlace = place;
        point = new GLatLng(
                        place.Point.coordinates[1],
                        place.Point.coordinates[0]);
        marker = new GMarker(point);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(
            '<form id="entityMark" action="#" onsubmit="setEntityData(); return false">' +
            '<table>' +
            '<tr><td><b>Entidade:</b></td><td><input id="ettCode" type="text" style="width:100px" value="' + document.forms["formEntity"].elements["EntityAbbr"].value + '"/></td><td><input id="ettName" type="text" style="width:250px" value="' + document.forms["formEntity"].elements["EntityName"].value + '"/></td></tr>' +
            '<tr><td><b>Telefone:</b></td><td colspan="2"><input id="ettPhone" type="text" style="width:100px" value="' + document.forms["formEntity"].elements["Phone"].value + '"/><b> Fax:</b><input id="ettFax" type="text" style="width:100px" value="' + document.forms["formEntity"].elements["Fax"].value + '"/></td></tr>' +
            '<tr><td><b>Email:</b></td><td colspan="2"><input id="ettEmail" type="text" style="width:150px" value="' + document.forms["formEntity"].elements["Email"].value + '"/></td></tr>' +
            '<tr><td><b>URL:</b></td><td colspan="2"><input id="ettURL" type="text" style="width:150px" value="' + document.forms["formEntity"].elements["URL"].value + '"/></td></tr>' +
            '<tr><td><b>Endereço:</b></td><td colspan="2">' + place.address + "</td></tr>" +
            '<tr><td><b>Lat.,Lon.:</b></td><td colspan="2">' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + "</td></tr>" +
            '<tr><td colspan="3" style="text-align:right"><input name="submit" type="submit" value="Actualizar ficha" /></td></tr></table>' +         
            '</form>'
            );
    }
}



function setDirections() {
    if (geocoder) {
        var oForm = document.forms["formEntity"];
        var oAddress1 = oForm.elements["Address1"]
        var oAddress2 = oForm.elements["Address2"]
        var oPostalCode = oForm.elements["PostalCode"];
        var oCity = oForm.elements["City"];
        var oLatLng = oForm.elements["LatLng"]
        var strSearch = oAddress1.value + ", " + oPostalCode.value + " " + oCity.value + ", " + oAddress2.value;

        if (oLatLng.value.length > 0) {
            strSearch = oLatLng.value;
        }  
               
        // if not empty address, continue
        if (((oAddress1.value + oPostalCode.value + oCity.value + oAddress2.value) != "") || (oLatLng.value.length > 0)) {
            geocoder.getLocations(strSearch, function(addresses) {showAddress(addresses)});
        }         
    }    
}



function handleErrors(statusCode) {
    //if no status code is passed
    if (typeof statusCode == "undefined") {
        statusCode = map.getStatus().code;
    }

    if (statusCode == G_GEO_UNKNOWN_ADDRESS)  
        alert("Endereço(s) inexistente(s). O endereço pode ser novo ou estar incorrecto.\n\nCódigo de Erro: " + statusCode);
    else if (statusCode == G_GEO_SERVER_ERROR)
        alert("O pedido de geocodificação não pode ser processado.\n - Motivo desconhecido, verifique o zoom do mapa.\n\n Código Erro: " + statusCode);
    else if ((statusCode == G_GEO_MISSING_QUERY) || (statusCode == G_GEO_MISSING_ADDRESS))
        alert("Um ou mais critérios de pesquisa em falta. \n\n Verifique que os endereços estão ou as coordenadas geográficas correctamente preenchidos.\n\n Código de erro: " + statusCode);
    else if (statusCode == G_GEO_BAD_KEY)
        alert("Chave inválida.\n\n Código de erro: " +statusCode);
    else if (statusCode == G_GEO_TOO_MANY_QUERIES)
        alert("Foram ultrapassados os limites de pedidos para 24 horas ou foram submetidos demasiados pedidos em simultâneo.\n\n Código de erro: " +statusCode);        
    else if (statusCode == G_GEO_BAD_REQUEST)
        alert("A direcção não foi processada com sucessso\n Códgio Erro: " + map.getStatus().code);
    else if (statusCode == G_GEO_UNAVAILABLE_ADDRESS)
        alert("Foram utilizadas localizações indispiníveis devido a constrangimentos legais ou contratuais.\n Códgio de Erro: " + statusCode);        
    else if (statusCode == G_GEO_UNAVAILABLE_ADDRESS)
        alert("Impossível gerar uma rota.\n\nNão existe um rota possível para os pontos indicados ou a precisão dos dados da região é demasiado baixa.\n Códgio de Erro: " + statusCode);        
    else alert("Ocorreu um erro desconhecido.");
}



function Trim(str) { return str.replace(/^\s+|\s+$/g, ""); }
        